const util = require('../../utils/util');
const app = getApp();
const defaultLogName = {
  work: '计时',
};
Page({
  data: {
    hiddenmodalput: true,
    remainTimeText: '',
    showTime: 0,
    endTime: 0,
    timerType: 'work',
    record: {},
    completed: false, //是否结束
    isRuning: false, //是否运行
    isStop: false,
    isFirst: false,

    selectShow: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    selectData: [], //下拉列表的数据
    index: 0, //选择的下拉列表下标
  },
  onLoad: function () {
    this.getUserHabits(); // 直接调用获取用户习惯的函数
  },
  //点击下拉显示框
  selectTap() {
    this.setData({
      selectShow: !this.data.selectShow
    });
  },
  //点击下拉列表
  optionTap(e) {
   //获取点击的下拉列表的下标
    let Index = e.detail.value;
    this.setData({
      index: Index,
      selectShow: !this.data.selectShow
    });
    this.changeLogName();
  },

  modalinput: function () {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    });
  },
  //取消
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },
  //确认
  confirm: function () {
    this.setData({
      hiddenmodalput: true,
    });
    this.onShow();
  },
  setTime: function (e) {
    this.setData({
      'workTime': e.detail.value
    });
    //记录
    wx.setStorage({
      key: 'workTime',
      data: e.detail.value
    });
  },
  onShow: function () {
    this.getUserHabits(); // 直接从后端获取
    if (this.data.isRuning) return;
    let workTime = util.formatTime(wx.getStorageSync('workTime'), 'HH');
    this.setData({
      workTime: workTime,
      remainTimeText: workTime + ':00'
    });
  },
  startTimer: function (e) {
    let startTime = Date.now();
    let isRuning = this.data.isRuning;
    let timerType = e.target.dataset.type;
    let showTime = this.data[timerType + 'Time'];
    let keepTime = showTime * 60 * 1000;
    let logName = this.logName || defaultLogName[timerType];
    let isStop = this.data.isStop;
    let keepM = parseInt((keepTime / 1000 - this.data.showTime) / 60);
    let keepS = (keepTime / 1000 - this.data.showTime) % 60;
    if (!this.data.isFirst) {
      this.setData({
        endTime: keepTime + startTime,
        isFirst: !this.data.isFirst
      });
    }
    if (!isRuning) {
      this.timer = setInterval((function () {
        this.updateTimer();
      }).bind(this), 1000);
    } else {
      this.setData({
        isStop: !isStop,
        isFirst: !this.data.isFirst
      });
      let record = this.data.record;
      record.keepM = keepM;
      record.keepS = keepS;
      this.saveLog(this.data.record);
      let now = new Date();
      let timer_Year = now.getFullYear().toString();
      let timer_Month = (now.getMonth() + 1).toString();
      let timer_Day = now.getDate().toString();
      let actualTime = (this.data[timerType + 'Time'] * 60) - this.data.showTime; // 实际用时（秒）

      wx.request({
        url: 'http://127.0.0.1:3001/api/timer',
        method: 'POST',
        data: {
          habit_id: this.data.index, // 你下拉选择的习惯id，需和实际习惯id对应
          user_id: wx.getStorageSync('userId') || app.globalData.user_id, // 你有用户系统就用openid，没有可以先写死
          timer_SetTime: this.data[timerType + 'Time'], // 设定的定时时长（秒）
          timer_ActualTime: actualTime, // 实际用时（秒）
          timer_Year: timer_Year,
          timer_Month: timer_Month,
          timer_Day: timer_Day,
          timer_type: 1 // 你可以自定义类型
        },
        success: () => {
          wx.showToast({
            title: '计时记录已保存'
          });
        },
        fail: () => {
          wx.showToast({
            title: '保存失败',
            icon: 'none'
          });
        }
      });
      this.stopTimer();
    }

    this.setData({
      isRuning: !isRuning,
      completed: false,
      timerType: timerType,
      remainTimeText: showTime + ':00',
      showTime: showTime * 60,
    });
   
    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;

    this.data.record = {
      name: logName,
      startTime: now,
      keepTime: keepTime / 60 / 1000, //keepTime/60/1000
      endTime: keepTime + startTime,
      keepM: keepM,
      keepS: keepS,
      year: year,
      month: month,
      day: now.getDate()
    };
  },
  suspendTimer: function () {
    let isStop = this.data.isStop;
    let showTime = this.data.showTime;
    let keepTime = showTime * 1000;

    let now = Date.now();
    this.setData({
      isStop: !isStop,
      completed: false,
      endTime: keepTime + now
    });
    if (!this.data.isStop) {
      this.timer = setInterval((function () {
        this.updateTimer();
      }).bind(this), 1000);
    } else {
      this.stopTimer();
    }

  },

  stopTimer: function () {
    this.timer && clearInterval(this.timer);
    this.setData({
      timer: null
    });
  },

  updateTimer: function () {
    let now = Date.now();
    let remainingTime = Math.round((this.data.endTime - now) / 1000);
    // let H = util.formatTime(Math.floor(remainingTime / (60 * 60)) % 24, 'HH');
    let M = util.formatTime(Math.floor(remainingTime / (60)) % 60, 'MM');
    let S = util.formatTime(Math.floor(remainingTime) % 60, 'SS');
    if (remainingTime > 0) {
      let remainTimeText = M + ':' + S;
      this.setData({
        remainTimeText: remainTimeText,
        showTime: remainingTime
      });
    } else if (remainingTime == 0) {
      this.setData({
        completed: true
      });
    }
  },
  changeLogName: function () {
    this.logName = this.data.selectData[this.data.index];
  },

  saveLog: function (record) {
    var records = wx.getStorageSync('records') || [];
    records.unshift(record);
    wx.setStorageSync('records', records);
  },
  getUserHabits: function () {
    const userId = wx.getStorageSync('userId') || app.globalData.user_id;

    if (!userId) {
      wx.showToast({
        title: '用户ID未找到',
        icon: 'none'
      });
      this.setData({
        selectData: ['未选择习惯']
      });
      return;
    }

    wx.request({
      url: 'http://127.0.0.1:3001/getUserHabit',
      method: 'GET',
      data: {
        userId: userId
      },
      success: (res) => {
        if (res.data && Array.isArray(res.data)) {
          // 直接使用后端返回的数据填充 selectData
          var tmp = new Array();
          tmp[0] = '未选择习惯';
          for (var i = 0; i < res.data.length; i++) {
            // 检查 habit_finishedTime 是否为空字符串或null，只添加未结束的习惯
            if (res.data[i].is_finished === 0) {
              var x = res.data[i].habit_name;
              tmp.push(x);
            }
          }
          this.setData({
            selectData: tmp
          }, () => {
          });
        } else {
          this.setData({
            selectData: ['未选择习惯']
          });
        }
      },
      fail: (err) => {
        console.error('获取用户习惯失败:', err);
        wx.showToast({
          title: '获取用户习惯失败',
          icon: 'none'
        });
        this.setData({
          selectData: ['未选择习惯']
        });
      }
    });
  },
});